<template>
  <div class="upload-file" :class="{ disabled: disabled }">
    <el-upload
      multiple
      :action="uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :show-file-list="false"
      :headers="headers"
      class="upload-file-uploader"
      ref="fileUpload"
    >
      <!-- 上传按钮 -->
      <el-button size="mini" type="primary">选取文件</el-button>
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize">
          大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
        </template>
        <template v-if="fileType">
          格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
        </template>
        的文件
      </div>
    </el-upload>
    <div v-if="disabled && fileList.length == 0">-</div>
    <!-- 文件列表 -->
    <transition-group
      class="upload-file-list el-upload-list el-upload-list--text"
      name="el-fade-in-linear"
      tag="ul"
    >
      <li
        :key="file.url + index"
        class="el-upload-list__item ele-upload-list__item-content"
        v-for="(file, index) in fileList"
      >
        <div class="link" @click="onFileLinkClick(file)">
          <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
        </div>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index)" type="danger"
            >删除</el-link
          >
        </div>
      </li>
    </transition-group>
  </div>
</template>

<script>
import { getAccessToken } from "@/utils/auth";
import { disable } from "ol/rotationconstraint";

export default {
  name: "FileUpload",
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 9,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 10,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf", "png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    valueType: {
      type: String,
      default: "array", // string、array
    },
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl:
        process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload", // 请求地址
      headers: { Authorization: "Bearer " + getAccessToken() }, // 设置上传的请求头部
      fileList: [],
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          let list = [];
          if (this.valueType === "string") {
            list = this.value.split(",");
          } else {
            list = JSON.parse(this.value);
          }
          // 然后将数组转为对象数组
          this.fileList = list.map((item) => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    onFileLinkClick(row) {
      this.$download.fetchUrl(row.url, row.name);
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$modal.msgError(
            `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
          );
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 0) {
        // edit by 芋道源码
        let name = this.getNoRepeatFileName(file.name);
        this.uploadList.push({ name: name, url: res.data });
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    /**
     * 向文件名数组添加新文件，自动处理重名
     * @param {string} newFile - 要添加的新文件名
     * @returns {string} 不重复的文件名
     */
    getNoRepeatFileName(newFile) {
      const existingFiles = [...this.fileList, ...this.uploadList].map(
        (file) => file.name
      );

      // 提取文件名和扩展名
      const getFileParts = (filename) => {
        const lastDotIndex = filename.lastIndexOf(".");
        if (lastDotIndex === -1) {
          return { name: filename, ext: "" };
        }
        return {
          name: filename.substring(0, lastDotIndex),
          ext: filename.substring(lastDotIndex),
        };
      };

      // 转义正则表达式特殊字符
      const escapeRegExp = (string) => {
        return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
      };

      // 主逻辑
      let { name, ext } = getFileParts(newFile);

      // 精确匹配基本文件名（不带后缀）
      const baseNameRegex = new RegExp(
        `^${escapeRegExp(name)}(\\(\\d+\\))?${escapeRegExp(ext)}$`
      );
      const duplicates = existingFiles.filter((file) =>
        baseNameRegex.test(file)
      );

      // 如果没有重复，直接返回原文件名
      if (duplicates.length === 0) {
        return newFile;
      }

      // 提取已有的数字后缀
      const existingNumbers = duplicates.map((file) => {
        const match = file.match(
          new RegExp(`^${escapeRegExp(name)}\\((\\d+)\\)${escapeRegExp(ext)}$`)
        );
        return match ? parseInt(match[1]) : 0;
      });

      // 计算新的数字后缀（最大数字 + 1）
      const newNumber = Math.max(0, ...existingNumbers) + 1;
      const newFileName = `${name}(${newNumber})${ext}`;

      return newFileName;
    },
    // 删除文件
    handleDelete(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.listToString(this.fileList));
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      if (this.valueType === "string") {
        return list.map((e) => e.url).join(separator || ",");
      } else {
        return JSON.stringify(list);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.upload-file {
  &.disabled {
    .upload-file-list {
      .el-upload-list__item {
        margin-top: 0;
        &.ele-upload-list__item-content {
          > :deep(.el-link) {
            margin-left: 0;
          }
        }
      }
    }
  }
}
.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list {
  .el-upload-list__item {
    border: 1px solid var(--searchBox-color);
    line-height: 36px;
    margin: 0px;
    position: relative;
    & + .el-upload-list__item {
      margin-top: 10px;
    }
    .link {
      cursor: pointer;
      &:hover {
        color: var(--input-color);
      }
    }
    &.ele-upload-list__item-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: inherit;

      > :deep(.el-link) {
        margin-left: 10px;

        .el-link--inner {
          color: #333;
        }

        &:hover {
          .el-link--inner {
            color: #1890ff;
          }
        }
      }
    }

    &:hover {
      border-color: var(--input-color);
      background-color: transparent;
    }
  }
}

.ele-upload-list__item-content-action .el-link {
  margin-left: 5px;
  margin-right: 10px;
  white-space: nowrap;
}
</style>
